package fr.upmf.miam.imageannotation;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Gallery;

public class ImageAnnotationGallery extends Activity implements OnItemClickListener, OnClickListener {

	private Uri baseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
	private Gallery g;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_annotation_gallery);
		Context ctx = getApplicationContext();
		g = (Gallery) findViewById(R.id.gallery);
		Cursor c = ctx.getContentResolver().query( baseUri, new String[] {MediaStore.Images.Media._ID}, null, null, null);

		g.setAdapter(new ImageAnnotationGalleryAdapter(this, c));
		g.setOnItemClickListener(this);
		Button b = (Button) findViewById(R.id.gallery_button_annote_it);
		b.setOnClickListener(this);
	}


	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.image_annotation_gallery, menu);
		return true;
	}
	
	public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
		Uri uri = Uri.withAppendedPath(Images.Media.EXTERNAL_CONTENT_URI, id+"");
		
		//Ajoute l'image selectionnee dans la base de donnée.
		ContentValues cv = new ContentValues();
		cv.put(ImageAnnotationContract.Picture.URI, uri.toString());
		Uri imgUriPicture = getContentResolver().insert(ImageAnnotationContract.Picture.CONTENT_URI, cv);
		
		//Création de l'intent pour l'envoyer à l'activité de notation
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_EDIT);
		intent.setDataAndType(imgUriPicture, "image/*");
		startActivity(intent);
	}

	public void onClick(View v) {		
		int id = (int) g.getSelectedItemId();
		Uri uri = Uri.withAppendedPath(Images.Media.EXTERNAL_CONTENT_URI, id+"");
		
		//Ajoute l'image selectionnee dans la base de donnée.
		ContentValues cv = new ContentValues();
		cv.put(ImageAnnotationContract.Picture.URI, uri.toString());
		Uri imgUriPicture = getContentResolver().insert(ImageAnnotationContract.Picture.CONTENT_URI, cv);
		
		//Création de l'intent pour l'envoyer à l'activité de notation
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_EDIT);
		intent.setDataAndType(imgUriPicture, "image/*");
		startActivity(intent); 
    }
}
